package delayQueue;

import java.util.*;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;

public class DelayQueueServiceImpl<T extends Delayed> implements DelayQueueService<T>{
    Map<String,DelayQueue<T>> delayQueueMap = new HashMap<>();


    @Override
    public DelayQueue<T> addDelayQueue(String queueName) {
        DelayQueue<T> delayQueue = new DelayQueue<>();
        delayQueueMap.putIfAbsent(queueName,delayQueue);
        return delayQueue;
    }

    @Override
    public void addElements(String queueName, T... t) {
        DelayQueue<T> delayQueue = delayQueueMap.get(queueName);
        if (delayQueue == null){
            delayQueue = addDelayQueue(queueName);
        }
        delayQueue.addAll(Arrays.asList(t));
    }

    @Override
    public void addElement(String queueName, T t) {
        DelayQueue<T> delayQueue = delayQueueMap.get(queueName);
        if (delayQueue == null){
            delayQueue = addDelayQueue(queueName);
        }
        delayQueue.add(t);
    }


    @Override
    public DelayQueue<T> getDelayQueue(String queueName) {
        return delayQueueMap.get(queueName);
    }

    @Override
    public void exeDelayTask() {
        List<Delayed> exeTaskList = new ArrayList<>();
        delayQueueMap.forEach((queueName,queue)->{
            queue.drainTo(exeTaskList);
        });

        for (Delayed exeTask : exeTaskList) {
            if (exeTask instanceof DelayQueueElement){
                ((DelayQueueElement)exeTask).getTask().execute();
            }
        }
    }
}
